<template>
  <section>
    <el-form ref="editForm" :model="editForm" label-width="80px" @submit.prevent="onSubmit"
             style="margin:20px;min-width:600px;">

      <el-form-item label="所属分类">
        <template>
          <div style="width: 300px;display: inline-block;">
            <el-select v-model="editForm.category_id" placeholder="请选择">
              <el-option
                v-for="item in category"
                :key="item.id"
                :label="item._name"
                :value="item.id">
              </el-option>
            </el-select>
          </div>
        </template>
      </el-form-item>


      <el-form-item label="商品名称">
        <template slot-scope="scope">
          <div style="width: 300px;display: inline-block;">
            <el-input v-model="editForm.title" auto-complete="on"></el-input>
          </div>
        </template>
      </el-form-item>
      <el-form-item label="商品描述">
        <template>
          <div style="width: 600px;">
            <el-input type="textarea" v-model="editForm.description"></el-input>
          </div>
        </template>
      </el-form-item>
      <el-form-item label="库存">
        <template slot-scope="scope">
          <div style="width: 300px;display: inline-block;">
            <el-input v-model="editForm.inventory" auto-complete="on"></el-input>
          </div>
          <span style="margin-left: 10px;color: #48576A;">例如：30(份)-输入数字</span>
        </template>
      </el-form-item>

      <el-form-item label="售价">
        <template slot-scope="scope">
          <div style="width: 300px;display: inline-block;">
            <el-input v-model="editForm.price" auto-complete="on"></el-input>
          </div>
          <span style="margin-left: 10px;color: #48576A;">例如：59(元)-输入数字</span>
        </template>
      </el-form-item>

      <el-form-item label="标价">
        <template slot-scope="scope">
          <div style="width: 300px;display: inline-block;">
            <el-input v-model="editForm.orgin_price" auto-complete="on"></el-input>
          </div>
          <span style="margin-left: 10px;color: #48576A;">例如：59(元)-输入数字</span>
        </template>
      </el-form-item>
      <el-form-item label="是否在售">
        <template>
          <div style="width: 300px;display: inline-block;">
            <el-select v-model="editForm.is_sale" placeholder="请选择">
              <el-option
                v-for="item in saleList"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </div>
        </template>
      </el-form-item>

      <el-form-item label="附加属性">
        <div class="addAttr">
          <span class="attr" @click="addDomain">添加+</span>
        </div>
        <el-form>
          <el-form-item
                  v-for="(domain, index) in attrList"
                  :key="domain.key"
                  :prop="'attrList.' + index + '.k'">
            <el-input v-model="domain.k" style="display: inline-block;width: 150px;margin-right: 20px;margin-top:10px;"></el-input>
            <el-input v-model="domain.v" style="display: inline-block;width: 150px;margin-top:10px;"></el-input>
            <el-button @click.prevent="handleMove(index)">上移</el-button>
            <el-button @click.prevent="removeDomain(index)">删除</el-button>
          </el-form-item>
        </el-form>
      </el-form-item >
      <el-form-item label="发货日期">
        <template slot-scope="scope">
          <div style="width: 300px;display: inline-block;">
            <el-date-picker v-model="editForm.shipping_time" type="date" placeholder="选择日期"></el-date-picker>
            <!--<el-input v-model="editForm.shipping_time" auto-complete="on"></el-input>-->
          </div>
          <span style="margin-left: 10px;color: #48576A;">例如：20(天)-输入数字</span>
        </template>
      </el-form-item>
      <el-form-item label="列表图片">
        <template>
          <div class="p-listPic-upload">
            <el-button type="success">上传<i class="el-icon-upload el-icon--right"></i></el-button>
            <span class="upload_plant_pic"><input type="file" name="file" class="cfg_upload_pic" @change="upInputOnchange($event, 1, -1)"></span>
          </div>
          <div style="width: 120px;height: 80px; background: #ffffff;overflow: hidden;margin-top: 20px" v-if="editForm.list_img">
            <img :src="editForm.list_img" />
          </div>
        </template>
      </el-form-item>
      <el-form-item label="详情图片">
        <template v-if="editForm.detail_img">
          <div class="p-listPic-upload">
            <el-button type="success">上传<i class="el-icon-upload el-icon--right"></i></el-button>
            <span class="upload_plant_pic"><input type="file" name="file" class="cfg_upload_pic" @change="upInputOnchange($event, 2, -1)"></span>
          </div>
          <div v-for="(item, index) in editForm.detail_img" style="position: relative;">
            <div style="width: 400px;display: inline-block;">
              <el-input :value="item.url" :key="index" auto-complete="on" style="margin-top: 5px;" readonly></el-input>
            </div>
            <div class="p-pic-upload">
              <el-button type="success">修改<i class="el-icon-upload el-icon--right"></i></el-button>
              <span class="upload_plant_pic_edit"><input type="file" name="file" class="cfg_upload_pic" @change="upInputOnchange($event, 2, index)"></span>
            </div>
          </div>
          <div style="margin-top: 5px;overflow: hidden;display: inline-block" v-for="(item, index) in editForm.detail_img" v-if="item.type == '1'">
            <img @click="deleteDetailPic(index)" :src="item.url" alt="" :key="index" style="width: 140px;height: 80px;margin-right: 5px;cursor: pointer;">
          </div>
        </template>
      </el-form-item>

      <el-form-item label="商品详情">
        <editer ref="editer" :content="content"></editer>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click.native="editSubmit">提交</el-button>
        <el-button @click.native.prevent>取消</el-button>
        <el-button type="primary" @click.native="_writed">写入信息</el-button>
      </el-form-item>

    </el-form>
  </section>
</template>

<script type="text/ecmascript-6">
  import { apiTree } from '../../apiTree'
  import NProgress from 'nprogress'
  import util from '../../util'
  import editer from '../common/ueditor'
  import { returnEditerHtml } from '../../vuex/getters'

  export default {
    components: {
      editer
    },
    data() {
      return {
        showGoods: false,
        editForm: {
          id: 1,
          farm_id: '',
          category_id: '',
          title: '',
          description: '',
          list_img: '',
          detail_img: [],
          goods_attr: 0,
          orgin_price: 0,
          price: '',
          inventory: 0,
          is_sale: 0,
          shipping_time: '',
          sort_order: 0
        },
        saleList: [
          {'value': '1','label': '在售'},
          {'value': '0','label': '下架'}
        ],
        content: '',
        attrList: [],
        category: []
      }
    },
    methods: {
        // 修改商品属性逻辑
        removeDomain(index) {
          this.attrList.splice(index, 1)
        },
        addDomain() {
          this.attrList.push({
            k: '',
            v: '',
            key: Date.now()
          });
        },
        // 向上移动
        handleMove (index) {
          if (index > 0) {
            let list = this.attrList[index]
            let _temp = util.cloneObj(this.attrList);
            _temp[index] = _temp[index - 1]
            _temp[index - 1] = list;
            this.attrList = _temp;
          }
        },
      // 获取商品分类和品类
      getTag() {
        apiTree('goods/index', 'goods/tag').then((res) => {
          if (res.s === 1) {
            this.category = res.d.cate_data;
            NProgress.done();
          } else {
            this.$message.error(res.err_str)
          }
        })
      },
      // 上传商品照片
      upInputOnchange(e, _type, index) {
        var _that = this
        let file = e.target.files[0]
        let _reader = new FileReader()
        _reader.readAsDataURL(file)
        _reader.onload = function() {
          let _file = this.result
          let param = {'file': _file, 'type': 3}
          apiTree('upload/index', 'plant/upload', param,'POST').then((res) => {
            if (res.s === 1) {
              // 列表图片
              if (_type === 1) {
                _that.editForm.list_img = res.d.url
              }
              // 详情图片
              if (_type === 2) {
                _that.$nextTick(() => {
                  if (index < 0) {
                    _that.editForm.detail_img.push({type: '1', url: res.d.url})
                  } else {
                    _that.editForm.detail_img[index]['url'] = res.d.url;
                  }
                  _that.$set(_that.editForm.detail_img, _that.editForm.detail_img);
                })
              }
            }
          })
        }
      },
      deleteDetailPic(_index) {
        this.editForm.detail_img.splice(_index, 1);
      },
      removePic(_file) {
        this.editForm.detail_img.forEach((item, key) => {
          if (_file.name === item.name) {
            this.editForm.detail_img.splice(key, 1)
          }
        })
      },
      editSubmit: function () {
        this.$refs.editForm.validate(() => {
          this.$refs.editer.$emit('getUeditorContent')
          this.editForm.content = returnEditerHtml(this.$store.state)
          this.editLoading = true;
          if (!util.isNumber(this.editForm.category_id) || util.isEmpty(this.editForm.category_id)) {
            this.$message.error('请选择商品分类');
            return ;
          }
          if (util.isEmpty(this.editForm.title)) {
            this.$message.error('请填写标题');
            return ;
          }
          if (!util.isNumber(this.editForm.price) || !util.isNumber(this.editForm.orgin_price)) {
            this.$message.error('价格应为数字');
            return ;
          }
          if (!util.isNumber(this.editForm.inventory)) {
            this.$message.error('库存应为数字');
            return ;
          }
//          if (!util.isNumber(this.editForm.shipping_time)) {
//            this.$message.error('周期应为数字');
//            return ;
//          }
          if (util.isEmpty(this.editForm.description)) {
            this.$message.error('商品描述不能为空');
            return ;
          }
          if (util.isEmpty(this.editForm.list_img)) {
            this.$message.error('列表图片不能为空！')
            return
          }
          if (util.isEmpty(this.editForm.detail_img)) {
            this.$message.error('相册图片不能为空！')
            return
          }
//          let day = '下单后' + this.editForm.shipping_time + '天内发货';
//          this.attrList.push({ 'k': '发货周期', 'v': day });
          this.editForm.shipping_time = parseInt(new Date(this.editForm.shipping_time).getTime()) / 1000;
          this.editForm.goods_attr = this.attrList;
          apiTree('goods/index', 'goods/setGoods', this.editForm, 'POST').then((res) => {
            if (res.s === 1) {
              NProgress.done();
              this.$message({
                message: '提交成功',
                type: 'success'
              });
              this.$router.push('/goods/index');
            } else {
              this.editLoading = false;
              this.$message.error(res.err_str)
            }
          })
        })
      },
      editList: function () {
        let param = {'id': this.$route.params.id}
        apiTree('goods/index', 'goods/editGoodsList', param).then((res) => {
          let row = res.d.data[0]
          this.editForm = {
              id: row.id,
              farm_id: row.farm_id,
              category_id: row.category_id,
              title: row.title,
              description: row.description,
              list_img: row.list_img,
              detail_img: row.detail_img,
              goods_attr: row.goods_attr,
              orgin_price: (row.orgin_price / 100 ).toFixed(2),
              shipping_time: util.formatDate.format(new Date(row.shipping_time * 1000), 'yyyy-MM-dd'),
              price: (row.price / 100).toFixed(2),
              inventory: row.inventory,
              is_sale: row.is_sale
          }
          this.attrList = res.d.data[0].goods_attr;
          this.content = res.d.data[0].content
          for (let i = 0; i < this.attrList.length; i++) {
              if (this.attrList[i].k == "发货周期") {
                  this.attrList.splice(i,1);
              }
          }
        })
      },
      _writed() {
        this.$refs.editer.$emit('setUeditorContent')
      }
    },
    created() {
      this.editList();
      this.getTag()
    },
    mounted() {
      let that = this
      setTimeout(function(){
        that.$refs.editer.$emit('setUeditorContent')
      }, 400)
    }
  }
</script>

<style scoped lang="stylus" rel="stylesheet/stylus">
  .p-listPic-upload
    display inline-block
    margin-left 10px
    position relative
    cursor pointer
    .upload_plant_pic
      display block
      width 80px
      height 35px
      cursor pointer
      position absolute
      top 0px
      left 0px
      opacity 0
      & input[type=file]
        display block
        cursor pointer
        width 80px
        height 35px
  .p-pic-upload
    position absolute
    top 5px
    left 410px
    .upload_plant_pic_edit
      display block
      width 80px
      height 35px
      cursor pointer
      position absolute
      top 0px
      left 0px
      opacity 0
      & input[type=file]
        display block
        cursor pointer
        width 80px
        height 35px
  .p-pic-old-input
    display inline-block
    width 500px
  .addAttr
    width 100%
    height 50px
    .attr
      color #00b7ee
  .attrBList
    width 100%
    height 50px
    border-bottom #333333 1px solid
    & span
      display inline-block
      width 130px
      line-height 50px
      color #666666
</style>
